import { createI18n } from 'vue-i18n'
import zhCN from './zh-CN'
import enUS from './en-US'

// The messages will be loaded asynchronously
const messages = {
  'zh-CN': zhCN,
  'en-US': enUS
}

// Get user's language preference from localStorage or browser
const getDefaultLocale = (): string => {
  // Try to get from localStorage first
  const stored = localStorage.getItem('locale')
  if (stored && Object.keys(messages).includes(stored)) {
    return stored
  }

  // Get from browser language
  const browserLang = navigator.language
  if (browserLang.startsWith('zh')) {
    return 'zh-CN'
  } else if (browserLang.startsWith('en')) {
    return 'en-US'
  }

  // Default to Chinese
  return 'zh-CN'
}

const i18n = createI18n({
  legacy: false,
  locale: getDefaultLocale(),
  fallbackLocale: 'zh-CN',
  messages,
  globalInjection: true
})

export default i18n

// Export the change locale function
export const setLocale = (locale: string) => {
  if (Object.keys(messages).includes(locale)) {
    i18n.global.locale.value = locale
    localStorage.setItem('locale', locale)
    // Set HTML lang attribute
    document.documentElement.lang = locale
  }
}

// Export available locales
export const availableLocales = [
  { code: 'zh-CN', name: '简体中文' },
  { code: 'en-US', name: 'English' }
] as const